<template>
  <div id="form-design-template" v-loading="loading">
    <el-header>
      <div class="header-left">
        <el-button @click="getBack" :icon="ArrowLeft" circle size="small"></el-button>
        <svg-icon icon-class="txt"></svg-icon>

        <!-- <div slot="content">{{ templateForm.formName || "未命名表单" }}</div> -->
        <span class="header-name">{{ templateForm.formName || "未命名表单" }}</span>

      </div>
      <div class="header-center">
        <span @click="getTabChange(item.name)" v-for="(item, index) in herderNav" :key="index" class="center-tab"
          :class="activeName == item.name ? 'active-center-tab' : ''">
          <span class="center-text">{{ index + 1 }} </span>
          {{ item.label }}
        </span>
      </div>
      <div>
        <el-button @click="getSaveOrPublish('unPublish')" :icon="FolderChecked" round>保存</el-button>
        <el-button v-if="!templateForm.id || templateForm.status == 'unPublish'" @click="getSaveOrPublish('publish')"
          :icon="Promotion" type="primary" round>
          发布
        </el-button>
      </div>
    </el-header>
    <el-container v-show="activeName == 'formMessage'" class="form-message">
      <el-form :model="templateForm" label-position="top" label-width="80px">
        <el-form-item label="表单封面">
          <el-upload class="upload-demo" ref="upload" :limit="1" list-type="picture-card"
            action="#" accept="image/jpeg,image/png"
            :file-list="templateForm.cover" :auto-upload="false" :before-remove="getBeforeRemove"
            :on-preview="handlePictureCardPreview" :on-remove="getRemoveCover" :on-exceed="getExceed"
            :on-change="getChangeCover">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="表单名称">
          <el-input v-model="templateForm.formName" maxlength="20" />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select v-model="templateForm.applyType" placeholder="请选择业务类型">
            <el-option v-for="item in form_template_type" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择部门">
          <!-- <treeselect v-model="templateForm.deptId" :options="depts" :multiple="false" :normalizer="normalizer"
            placeholder="请选择部门" noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果" /> -->
          <el-tree-select v-model="templateForm.deptId" :data="depts"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }" value-key="deptId"
            placeholder="选择上级部门" check-strictly />
        </el-form-item>
      </el-form>
    </el-container>
    <div v-show="activeName == 'formDesign'" class="form-designer">
      <v-form-designer ref="VFDesigner" />
    </div>
  </div>
</template>


<script lang="ts" setup>
import VFormDesigner from "../../components/form-designer/index.vue"
// import Treeselect from 'vue3-treeselect'
// import 'vue3-treeselect/dist/vue3-treeselect.css'
import { ArrowLeft, Promotion, FolderChecked } from "@element-plus/icons-vue"
import type { UploadProps, UploadUserFile } from 'element-plus'
// import { listDept } from '@/api/system/dept/index'
import { getDeptAll, addSysFormDocTemp, updateFormJsonSysFormDocTemp,uploadOrdinary } from "@/api/formTemplate"



const { proxy } = getCurrentInstance() as ComponentInternalInstance

const { form_template_type } = toRefs<any>(proxy?.useDict('form_template_type'))

const router = useRouter()
const route = useRoute()
const templateForm = reactive({
  formName: "",
  cover: [],
  applyType: "",
  coverStorage: "",
  id: "",
  status: "",
  formJson: {},
  deptId: null
})
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

const activeName = ref("formMessage")
const herderNav = reactive([
  { label: "表单信息", name: "formMessage" },
  { label: "表单设计", name: "formDesign" },
])
const loading = ref(false)
const depts = ref([])
const VFDesigner = ref<any>(null)




const getDepts = () => {
  getDeptAll().then(res => {
    depts.value = getNewTree(res.data)
    getRouterQuery()
  })
}
const getNewTree = (data) => {
  return data.map(item => {
    if (item.children && item.children.length > 0) {
      item.children = getNewTree(item.children)
    } else {
      item.children = []
    }
    return item
  })
}
const getRouterQuery = () => {
  if (Object.entries(route.query).length != 0) {
    Object.assign(templateForm, route.query)
    templateForm.cover = []

    // templateForm.deptId = 100
  }
  if (route.query.deptId) {

    if (route.query.parentId == '0') {
      templateForm.deptId = Number(route.query.deptId)
    } else {
      templateForm.deptId = route.query.deptId
    }
  } else {
    templateForm.deptId = 100
  }
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const getChangeCover = (file, fileList) => {
  const isBig = file.size / 1024 < 500
  if (!isBig) {
    ElMessage.error("上传图片大小不能超过500kb")
    return false
  } else {
    uploadImg(fileList)
  }

}
const uploadImg = async (fileList: UploadFile) => {
  let formData = new FormData()
  formData.append('file', fileList[0].raw);
  formData.append('type', 'publicImages');
  formData.append('fileName', fileList[0].name.split('.')[0]);
  let obJson = {
    module: 'template',
  }
  formData.append('info', JSON.stringify(obJson));
  let res = await uploadOrdinary(formData)
  if (res.code == 200) {
    templateForm.coverStorage = res.data.url
    // fileUrl.value = res.data.storageIdConvert
    // fileUrl.value = info.storageIdConvert.toString();
  }
}
const getTabChange = (val: string) => {
  activeName.value = val
  if (activeName.value == "formDesign" && templateForm.id) {
    VFDesigner.value.setFormJson(JSON.parse(templateForm.formJson as string))
  }
}
const getBack = () => {
  ElMessageBox.confirm("未发布的内容将不会被保存，是否直接退出?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      VFDesigner.value.clearDesigner()
      router.push({ path: "templateManage/form-template" })
    })
}

// 发布 或 保存
const getSaveOrPublish = async (status) => {
  let fn1 = templateForm.cover.length != 0 || templateForm.coverStorage
  if (!fn1) {
    ElMessage.warning("请上传表单封面")
    return
  }
  let fn2 = !templateForm.formName || !templateForm.applyType || !templateForm.deptId
  // let fn2 = !this.templateForm.formName || !this.templateForm.applyType;
  if (fn2) {
    ElMessage.warning("请填写完整表单信息")
    return
  }
  loading.value = true
  let formData = new FormData()
  formData.append("formName", templateForm.formName)
  formData.append("status", status)
  // 判断 业务类型是否是 number
  const isNumber = typeof templateForm.applyType == "number"
  let applyTypeItem
  if (!isNumber) {
    // string 在businessTypeOptions数组取对应id
    applyTypeItem = form_template_type.value.find((item) => item.value == templateForm.applyType)
  }
  //  number 直接传值
  formData.append("applyType", isNumber ? templateForm.applyType : applyTypeItem.value)
  formData.append("deptId", templateForm.deptId)
  formData.append("coverStorage", templateForm.coverStorage)

  formData.append("formJson", JSON.stringify(VFDesigner.value.getFormJson()))

  //  没有id-新增接口
  if (!templateForm.id) {
    await addSysFormDocTemp(formData)
  } else {
    //  有id-修改接口
    formData.append("id", templateForm.id)
    await updateFormJsonSysFormDocTemp(formData)
  }
  let message = status == "publish" ? "发布成功" : "保存成功"
  ElMessage.success(message)
  VFDesigner.value.clearDesigner()
  loading.value = false
  router.push({ path: "/templateManage/form-template" })
}
const getBeforeRemove = (file, fileList) => {
  // return ElMessageBox.confirm("确定删除该图片吗？")
}

const getRemoveCover = (file, fileList) => {

}
const getExceed = (files, fileList) => {
  ElMessage.warning("上传图片个数不能超过1个")
}
onMounted(() => {
  getDepts()
  // getRouterQuery()
})


</script>
<style scoped lang="scss">
#form-design-template {
  height: 100vh;
  background: #f5f6f6;

  .el-header {
    display: flex;
    justify-content: space-between;
    height: 60px;
    line-height: 60px;
    background: #ffffff;
    color: #3d3d3d;
    font-size: 12px;
    font-weight: 500;
    border-bottom: 1px solid #e4e4e4;
    margin-bottom: 15px;

    .header-left {
      display: flex;
      align-items: center;

      .header-name {
        width: 120px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

      .svg-icon {
        width: 30px;
        height: 30px;
        margin: 0px 10px 0px 15px;
      }
    }

    .header-center {
      display: flex;
      justify-content: center;

      .center-tab {
        display: flex;
        // width: 115px;
        height: 100%;
        padding: 0px 25px;
        cursor: pointer;

        .center-text {
          font-size: 25px;
          color: #303133;
          margin-right: 3px;
        }
      }

      .active-center-tab {
        background: #ecf5ff;
        color: #409eff;
        border-bottom: 1px solid #409eff;

        .center-text {
          color: #409eff;
        }
      }
    }
  }

  .form-message {
    width: 642px;
    height: calc(100vh - 100px);
    margin: 0 auto;
    background-color: #ffffff;
    padding: 20px;

    .el-form {
      width: 100%;

      .upload-demo {
        display: flex;
        justify-content: flex-start;

        .el-upload__tip {
          margin-left: 10px;
          margin-top: 0px;
        }

        .el-image {
          width: 100px;
          height: 100px;
          margin-top: 20px;
        }
      }

      .item-type {
        display: flex;
        justify-content: flex-start;

        ::v-deep .el-form-item__content {
          margin-left: 10px;
        }
      }

      ::v-deep .el-form-item__label::before {
        content: "*";
        color: red;
        margin-right: 5px;
        top: -3px;
        position: relative;
      }
    }
  }
}
</style>
<style lang="scss">
#form-design-template {
  .form-designer {
    .full-height {
      height: calc(100vh - 78px) !important;
    }
  }
}
</style>
